package com.crazypos.config;

import com.alibaba.fastjson.JSON;
import com.crazypos.common.utils.RedisUtil;
import com.crazypos.common.utils.SecurityUtil;
import com.crazypos.constant.CommonConstant;
import com.crazypos.dao.RoleDao;
import com.crazypos.pojo.PermissionEntity;
import com.crazypos.pojo.RoleEntity;
import com.crazypos.pojo.vo.RoleAndPermissionVO;
import com.crazypos.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Component
@Order(2)
@Slf4j
public class RoleAndPermissionConfig implements CommandLineRunner {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IRoleService roleService;

    @Override
    public void run(String... args) throws Exception {
        List<RoleAndPermissionVO> result = roleService.initGetAllRolesAndPermissions();
        System.out.println(result);
        // ORGANIZATIONID_ROLEID:[PERMISSION_ID]
        for (RoleAndPermissionVO roleAndPermissions :
                result) {
            String key = SecurityUtil.createPermissionKey(roleAndPermissions.getOrganizationId(), roleAndPermissions.getId());

            List<String> permissionValueList = new ArrayList<>();
            for (PermissionEntity permission :
                    roleAndPermissions.getPermissionsList()) {
                System.out.println(permission.getValue());
                permissionValueList.add(permission.getValue());
            }

            // 将角色组的权限提前缓存到redis中
            redisUtil.hset(key, CommonConstant.PERMISSION_FIELDS_NAME, JSON.toJSONString(permissionValueList));
        }
    }

}
